import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router'
import store from '@/store'
import { setTitle, setToken, getToken } from '@/lib/util'
Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  mode: 'history'
})

// const HAS_LOGIN = false
// 全局前置守卫
router.beforeEach((to, from, next) => {
  to.meta && setTitle(to.meta.title)
  // if (to.name !== 'login') {
  //   if (HAS_LOGIN) next()
  // else {
  //   next({
  //     name: 'login'
  //   })
  // }
  const token = getToken()
  if (token) {
    store.dispatch('authorization', token).then(() => {
      if (to.name === 'login') next({ name: 'Home' })
      else next()
    }).catch(() => {
      setToken('')
      next({ name: 'login' })
    })
  } else {
    // if (HAS_LOGIN) next({ name: 'Home' })
    // else next()
    if (to.name === 'login') next()
    else next({ name: 'login' })
  }
})

router.beforeResolve((to, from, next) => {
  next()
})

router.afterEach((to, from) => {

})

export default router
